package com.tnsw.noxnox.settopbox;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.tnsw.coreutils.AsyncManager;

public class STBWebHandler implements HttpRequestHandler {

	private String tag = "STBWebHandler";
	private AsyncManager asyncManager;
	private Context context;

	public STBWebHandler(Context context) {
		this.context = context;
		this.asyncManager = AsyncManager.getInstance();
	}
	
	@Override
	public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
		Log.d(tag, "handle() is being called.");
		Log.d(tag, "method=" + request.getRequestLine().getMethod());
		Log.d(tag, "class=" + request.getClass().getName());
		Log.d(tag, "uri=" + request.getRequestLine().getUri());
		this.asyncManager.appendNetworkLog("stb: handle() is being called.");
		this.logRequestHeader(request);
		
		String url = "";
		String tempUrl = "http://temp" + request.getRequestLine().getUri();
		Log.d(tag, "tempUrl=" + tempUrl);
		Uri uri = Uri.parse(tempUrl);
		String command = uri.getLastPathSegment();
		Log.d(tag, "command=" + command);
		this.asyncManager.appendNetworkLog("stb: command=" + command);
		
		if (command.equals("scan")) {
			this.doScanCommand(request, response, context);
		} else if (command.equals("play")) {
			this.doPlayCommand(request, response, context);
		} else {
			Log.e(tag, "Command=" + command + " is invalid.");
		}
		
	}

	private void doPlayCommand(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
		String url = "";
		
		if (request instanceof BasicHttpEntityEnclosingRequest) {
			BasicHttpEntityEnclosingRequest entity = (BasicHttpEntityEnclosingRequest) request;
			byte[] data = EntityUtils.toByteArray(entity.getEntity());
			
			String dataStr = new String(data);
			Log.d(tag, "dataStr=" + dataStr);
			this.asyncManager.appendNetworkLog("stb: dataStr=" + dataStr);
			
			Uri uri = Uri.parse("http://test/a?" + dataStr);
			url = uri.getQueryParameter("url");
			this.asyncManager.appendNetworkLog("stb: url=" + url);
			
		}
		
		Intent intent = new Intent(this.context, com.tnsw.noxnox.settopbox.STBTVScreen.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("orientation", "none");
		intent.putExtra("url", url);
		this.context.startActivity(intent);		
	}
	
	private void doScanCommand(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
		response.setHeader("Content-type", "text/xml");
		final String respStr = "OK";
        HttpEntity entity = new EntityTemplate(new ContentProducer() {
        
			@Override
            public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
               
                    writer.write(respStr);
                    writer.flush();
            }});
       
        response.setHeader("Content-length", String.valueOf(respStr.length()));
        response.setEntity(entity);
        
		
	}
	
	private void logRequestHeader(HttpRequest request) {
		for (Header h : request.getAllHeaders()) {
			Log.d(tag, h.getName() + ":" + h.getValue());
			this.asyncManager.appendNetworkLog(h.getName() + ":" + h.getValue());
		}
	}

}
